﻿/**
* File: XmglxmxxService.cs
* Author: 汪杰
* Create Time:2025/2/21 13:53:00
* Email:15200358008@139.com
* 代码由TMCodeGenerator自动生成
**/
using AutoMapper;
using JSLCloud.App.Models.Xmglxmxx;
using JSLCloud.Attributes;
using JSLCloud.DBModel;
using JSLCloud.Framework;
using JSLCloud.Models;
using JSLCloud.Utilities.SqlSugar;
using JSLCloud.Utilities.WebApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;


namespace JSLCloud.App.Mes.Service
{
    /// <summary>
    /// IXmglxmxxService 实现类
    /// </summary>
    [UseDI(ServiceLifetime.Scoped,typeof(IXmglxmxxService))]
    public class XmglxmxxService : IXmglxmxxService
    {
        private readonly IDbContext _db;//数据库操作实例对象
        private readonly ILogger<XmglxmxxService> _log;//日志操作实例对象
        private readonly IMapper _mapper;//AutoMapper实例
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public XmglxmxxService(IDbContext dbContext, ILogger<XmglxmxxService> logger,IMapper mapper)
        {
            _db = dbContext;
            _log = logger;
            _mapper = mapper;
        }
        
        /// <summary>
        /// 获取xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，查询操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<List<XmglxmxxQueryModel>>> GetAsync(RequestGet requestObject)
        {
            try
            {
                List<XmglxmxxQueryModel> queryData = null;//查询结果集对象
                RefAsync<int> totalNumber = -1;//总记录数
                var query = _db.Instance.Queryable<XmglxmxxDbModel,XmjcgltxDbModel,XmjckhxxDbModel,XmjclcxxzbDbModel,XmjcqdxxDbModel>(
                    (t,t1,t2,t3,t4) => new object[]
                    {
                        JoinType.Left , t.Txid == t1.ID,
                        JoinType.Left , t.Khid == t2.ID,
                        JoinType.Left , t.Lcmb == t3.ID,
                        JoinType.Left , t.Qdid == t4.ID
                    });
                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    var conditionals = SqlSugarUtil.GetConditionalModels(requestObject.QueryConditions);
                    query.Where(conditionals);
                }
                
                //查询未删除数据
                query.Where("t.DELETEFLAG = 0");
                
                //排序条件
                if(requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0)
                {
                    foreach (var item in requestObject.OrderByConditions)
                    {
                        if (item.Condition.ToLower() != "asc" 
                            && item.Condition.ToLower() != "desc") continue;
                        query.OrderBy($"{item.Column} {item.Condition}");
                    }
                }
                
                //执行查询
                if (requestObject.IsPaging)
                {
                    queryData = await query.Select(
						(t, t1, t2, t3, t4) => new XmglxmxxQueryModel 
						{
							ID = t.ID,
							Createid = t.Createid,
							Createname = t.Createname,
							Createtime = t.Createtime,
							Updateid = t.Updateid,
							Updatename = t.Updatename,
							Updatetime = t.Updatetime,
							Deleteflag = t.Deleteflag,
							Khid = t.Khid,
							Txid = t.Txid,
							Erpbh = t.Erpbh,
							Sxq = t.Sxq,
							Shlx = t.Shlx,
							Txrs = t.Txrs,
							Rzfw = t.Rzfw,
							Csje = t.Csje,
							Jsje = t.Jsje,
							Htqdrq = t.Htqdrq,
							Bz = t.Bz,
                            Khmc = t2.Khmc,
                            Txgg = t1.Txgg,
                            Txmc = t1.Txmc,
                            Rzbz = t1.Rzbz,
                            Shr = t.Shr,
                            Shsj = t.Shsj,
                            Shzt = t.Shzt,
                            Pcshr = t.Pcshr,
                            Pcshsj = t.Pcshsj,
                            Pcshzt = t.Pcshzt,
                            Pczt = t.Pczt,
                            Xmzt = t.Xmzt,
                            Skzt = t.Skzt,
                            Skqrr = t.Skqrr,
                            Skqrsj = t.Skqrsj,
                            Kpqrr = t.Kpqrr,
                            Kpqrsj = t.Kpqrsj,
                            Kpzt = t.Kpzt,
                            Xmztqrr = t.Xmztqrr,
                            Xmztqrsj = t.Xmztqrsj,
                            Lxdh = t2.Lxdh,
                            Lxr = t2.Lxr,
                            Lxyx = t2.Lxyx,
                            Sfdcs = t.Sfdcs,
                            Dcslb = t.Dcslb,
                            Zsh = t.Zsh,
                            Zsjsrq = t.Zsjsrq,
                            Zsksrq = t.Zsksrq,
                            Zslb = t.Zslb,
                            Zydm = t.Zydm,
                            Htdz = t.Htdz,
                            Htje = t.Htje,
                            Htlx = t.Htlx,
                            Sf = t.Sf,
                            Lcmb = t.Lcmb,
                            Lcmbmc = t3.Lcmbmc,
                            Qdid = t.Qdid,
                            Qdmc = t4.Qdmc,
                            Txids = t.Txids
						})
                        .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber);
                }
                else
                {
                    queryData = await query.Select(
						(t, t1, t2, t3, t4) => new XmglxmxxQueryModel 
						{
							ID = t.ID,
							Createid = t.Createid,
							Createname = t.Createname,
							Createtime = t.Createtime,
							Updateid = t.Updateid,
							Updatename = t.Updatename,
							Updatetime = t.Updatetime,
							Deleteflag = t.Deleteflag,
							Khid = t.Khid,
							Txid = t.Txid,
							Erpbh = t.Erpbh,
							Sxq = t.Sxq,
							Shlx = t.Shlx,
							Txrs = t.Txrs,
							Rzfw = t.Rzfw,
							Csje = t.Csje,
							Jsje = t.Jsje,
							Htqdrq = t.Htqdrq,
							Bz = t.Bz,
                            Khmc = t2.Khmc,
                            Txgg = t1.Txgg,
                            Txmc = t1.Txmc,
                            Rzbz = t1.Rzbz,
                            Shr = t.Shr,
                            Shsj = t.Shsj,
                            Shzt = t.Shzt,
                            Pcshr = t.Pcshr,
                            Pcshsj = t.Pcshsj,
                            Pcshzt = t.Pcshzt,
                            Pczt = t.Pczt,
                            Xmzt = t.Xmzt,
                            Skzt = t.Skzt,
                            Skqrr = t.Skqrr,
                            Skqrsj = t.Skqrsj,
                            Kpqrr = t.Kpqrr,
                            Kpqrsj = t.Kpqrsj,
                            Kpzt = t.Kpzt,
                            Xmztqrr = t.Xmztqrr,
                            Xmztqrsj = t.Xmztqrsj,
                            Lxdh = t2.Lxdh,
                            Lxr = t2.Lxr,
                            Lxyx = t2.Lxyx,
                            Sfdcs = t.Sfdcs,
                            Dcslb = t.Dcslb,
                            Zsh = t.Zsh,
                            Zsjsrq = t.Zsjsrq,
                            Zsksrq = t.Zsksrq,
                            Zslb = t.Zslb,
                            Zydm = t.Zydm,
                            Htdz = t.Htdz,
                            Htje = t.Htje,
                            Htlx = t.Htlx,
                            Sf = t.Sf,
                            Lcmb = t.Lcmb,
                            Lcmbmc = t3.Lcmbmc,
                            Qdid = t.Qdid,
                            Qdmc = t4.Qdmc,
                            Txids = t.Txids
                        })
                        .ToListAsync();
                }

                foreach(var item in queryData)
                {
                    if (string.IsNullOrEmpty(item.Txids))
                    {
                        continue;
                    }

                    item.Txmc = string.Join(',', await _db.Instance.Queryable<XmjcgltxDbModel>()
                        .Where($" id in ({item.Txids})")
                        .Select(p => p.Txmc)
                        .ToListAsync());

                }

                //返回执行结果
                return ResponseUtil<List<XmglxmxxQueryModel>>.SuccessResult(queryData, totalNumber);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<List<XmglxmxxQueryModel>>.FailResult(null, ex.Message);
            }
        }

        /// <summary>
        /// 获取xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，查询操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<dynamic>> GetCertificateAsync(RequestGet requestObject)
        {
            try
            {
                var query = _db.Instance.Queryable<XmglxmxxDbModel>();
                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    var conditionals = SqlSugarUtil.GetConditionalModels(requestObject.QueryConditions);
                    query.Where(conditionals);
                }

                //查询未删除数据
                query.Where("DELETEFLAG = 0");
                var xmxx = await query.FirstAsync();
                var txids = new List<int>();

                if (!string.IsNullOrEmpty(xmxx.Txids))
                {
                    txids.AddRange(Array.ConvertAll(xmxx.Txids.Split(','), s => int.TryParse(s, out int i) ? i : 0));
                }
                else
                {
                    txids.Add(xmxx.Txid);
                }
                var queryData = await _db.Instance.Queryable<XmjcgltxDbModel, XmkhgltxDbModel>(
                    (t, t1) => new object[]
                    {
                        JoinType.Left , t.ID == t1.Txid
                    })
                    .Where((t, t1) => txids.Contains(t.ID) && t1.Khid == xmxx.Khid)
                    .Select((t,t1) => new
                    {
                        Txid = t.ID,
                        Txmc = t.Txmc,
                        t1.Zsh,
                        t1.Zsrq,
                        t1.Zsyxq,
                        t1.Zslb,
                        t1.Fhxzmh,
                        t1.Zsjg
                    })
                    .ToListAsync();

                if(queryData == null || queryData.Count == 0)
                {
                    var queryData2 = await _db.Instance.Queryable<XmjcgltxDbModel>()
                    .Where(t => txids.Contains(t.ID))
                    .Select(t => new
                    {
                        Txid = t.ID,
                        t.Txmc,
                        Zsh = "",
                        Zslb = "主证书",
                        Fhxzmh = "N",
                        Zsjg = "URS"
                    })
                    .ToListAsync();
                    return ResponseUtil<dynamic>.SuccessResult(queryData2);
                }

                //返回执行结果
                return ResponseUtil<dynamic>.SuccessResult(queryData);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<dynamic>.FailResult(null, ex.Message);
            }
        }

        /// <summary>
        /// 获取xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，查询操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<List<XmglxmxxQueryModel>>> GetSchedulingAsync(RequestGet requestObject)
        {
            try
            {
                List<XmglxmxxQueryModel> queryData = null;//查询结果集对象
                RefAsync<int> totalNumber = -1;//总记录数
                var query = _db.Instance.Queryable<XmglxmxxDbModel, XmjcgltxDbModel, XmjckhxxDbModel,XmjcqdxxDbModel>(
                    (t, t1, t2, t3) => new object[]
                    {
                        JoinType.Left , t.Txid == t1.ID,
                        JoinType.Left , t.Khid == t2.ID,
                        JoinType.Left , t.Qdid == t3.ID
                    });
                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    var conditionals = SqlSugarUtil.GetConditionalModels(requestObject.QueryConditions);
                    query.Where(conditionals);
                }

                //查询未删除数据
                query.Where("t.DELETEFLAG = 0");

                //排序条件
                if (requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0)
                {
                    foreach (var item in requestObject.OrderByConditions)
                    {
                        if (item.Condition.ToLower() != "asc"
                            && item.Condition.ToLower() != "desc") continue;
                        query.OrderBy($"{item.Column} {item.Condition}");
                    }
                }

                //执行查询
                if (requestObject.IsPaging)
                {
                    queryData = await query.Select(
                        (t, t1, t2, t3) => new XmglxmxxQueryModel
                        {
                            ID = t.ID,
                            Createid = t.Createid,
                            Createname = t.Createname,
                            Createtime = t.Createtime,
                            Updateid = t.Updateid,
                            Updatename = t.Updatename,
                            Updatetime = t.Updatetime,
                            Deleteflag = t.Deleteflag,
                            Khid = t.Khid,
                            Txid = t.Txid,
                            Erpbh = t.Erpbh,
                            Sxq = t.Sxq,
                            Shlx = t.Shlx,
                            Txrs = t.Txrs,
                            Rzfw = t.Rzfw,
                            Csje = t.Csje,
                            Jsje = t.Jsje,
                            Htqdrq = t.Htqdrq,
                            Bz = t.Bz,
                            Khmc = t2.Khmc,
                            Txgg = t1.Txgg,
                            Txmc = t1.Txmc,
                            Rzbz = t1.Rzbz,
                            Shr = t.Shr,
                            Shsj = t.Shsj,
                            Shzt = t.Shzt,
                            Pcshr = t.Pcshr,
                            Pcshsj = t.Pcshsj,
                            Pcshzt = t.Pcshzt,
                            Pczt = t.Pczt,
                            Xmzt = t.Xmzt,
                            Skzt = t.Skzt,
                            Skqrr = t.Skqrr,
                            Skqrsj = t.Skqrsj,
                            Kpqrr = t.Kpqrr,
                            Kpqrsj = t.Kpqrsj,
                            Kpzt = t.Kpzt,
                            Xmztqrr = t.Xmztqrr,
                            Xmztqrsj = t.Xmztqrsj,
                            Lxdh = t2.Lxdh,
                            Lxr = t2.Lxr,
                            Lxyx = t2.Lxyx,
                            Sfdcs = t.Sfdcs,
                            Dcslb = t.Dcslb,
                            Zsh = t.Zsh,
                            Zsjsrq = t.Zsjsrq,
                            Zsksrq = t.Zsksrq,
                            Zslb = t.Zslb,
                            Zydm = t.Zydm,
                            Htdz = t.Htdz,
                            Htje = t.Htje,
                            Htlx = t.Htlx,
                            Sf = t.Sf,
                            Qdid = t.Qdid,
                            Qdmc = t3.Qdmc,
                            Txids = t.Txids,
                        })
                        .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber);
                }
                else
                {
                    queryData = await query.Select(
                        (t, t1, t2, t3) => new XmglxmxxQueryModel
                        {
                            ID = t.ID,
                            Createid = t.Createid,
                            Createname = t.Createname,
                            Createtime = t.Createtime,
                            Updateid = t.Updateid,
                            Updatename = t.Updatename,
                            Updatetime = t.Updatetime,
                            Deleteflag = t.Deleteflag,
                            Khid = t.Khid,
                            Txid = t.Txid,
                            Erpbh = t.Erpbh,
                            Sxq = t.Sxq,
                            Shlx = t.Shlx,
                            Txrs = t.Txrs,
                            Rzfw = t.Rzfw,
                            Csje = t.Csje,
                            Jsje = t.Jsje,
                            Htqdrq = t.Htqdrq,
                            Bz = t.Bz,
                            Khmc = t2.Khmc,
                            Txgg = t1.Txgg,
                            Txmc = t1.Txmc,
                            Rzbz = t1.Rzbz,
                            Shr = t.Shr,
                            Shsj = t.Shsj,
                            Shzt = t.Shzt,
                            Pcshr = t.Pcshr,
                            Pcshsj = t.Pcshsj,
                            Pcshzt = t.Pcshzt,
                            Pczt = t.Pczt,
                            Xmzt = t.Xmzt,
                            Skzt = t.Skzt,
                            Skqrr = t.Skqrr,
                            Skqrsj = t.Skqrsj,
                            Kpqrr = t.Kpqrr,
                            Kpqrsj = t.Kpqrsj,
                            Kpzt = t.Kpzt,
                            Xmztqrr = t.Xmztqrr,
                            Xmztqrsj = t.Xmztqrsj,
                            Lxdh = t2.Lxdh,
                            Lxr = t2.Lxr,
                            Lxyx = t2.Lxyx,
                            Sfdcs = t.Sfdcs,
                            Dcslb = t.Dcslb,
                            Zsh = t.Zsh,
                            Zsjsrq = t.Zsjsrq,
                            Zsksrq = t.Zsksrq,
                            Zslb = t.Zslb,
                            Zydm = t.Zydm,
                            Htdz = t.Htdz,
                            Htje = t.Htje,
                            Htlx = t.Htlx,
                            Sf = t.Sf,
                            Qdid = t.Qdid,
                            Qdmc = t3.Qdmc,
                            Txids = t.Txids,
                        })
                        .ToListAsync();
                }

                queryData.ForEach(p =>
                {
                    if (!string.IsNullOrEmpty(p.Txids))
                    {
                        p.Txmc = string.Join(',', _db.Instance.Queryable<XmjcgltxDbModel>()
                            .Where($" id in ({p.Txids})")
                            .Select(p => p.Txmc)
                            .ToList());
                    }

                    var pclist = _db.Instance.Queryable<XmglxmxxlcDbModel, XmglxmxxpcDbModel>(
                        (t, t1) => new object[] { JoinType.Left, t.ID == t1.Xmlcid && t.Xmid == t1.Xmid })                    
                    .Where((t, t1) => t.Xmid == p.ID && t.Sfxcsh == "Y" && t.Shy != null)                    
                    .OrderBy((t, t1) => t.Lcxh, OrderByType.Asc)
                    .Select((t, t1) => new
                    {
                        t.ID,
                        t.Lcmc,
                        t.Lcxh,
                        t.Ksrq,
                        t.Jsrq,
                        t1.Shy,
                        t1.Rt
                    })
                    .ToList();
                    
                    if (pclist == null || pclist.Count < 1)
                    {
                        p.Pcxx = "";
                        return;
                    }
                    var lcid = pclist.OrderBy(p => p.Lcxh).Select(p => p.ID).Distinct();

                    foreach (var item in lcid)
                    {
                        var currList = pclist.Where(p => p.ID == item).ToList();
                        var currmx = currList.Select(p => $"{p.Shy}&nbsp;&nbsp;&nbsp;&nbsp;{(DateTime)p.Ksrq:MM-dd}&nbsp;&nbsp;&nbsp;&nbsp;{(DateTime)p.Jsrq:MM-dd}&nbsp;&nbsp;&nbsp;&nbsp;{p.Rt}");
                        p.Pcxx += $"<div>{currList[0].Lcmc}:&nbsp;&nbsp;";
                        foreach (var item2 in currmx)
                        {
                            p.Pcxx += item2 + "<br/>";
                        }
                        p.Pcxx += "</div>";
                    }

                    

                });

                //返回执行结果
                return ResponseUtil<List<XmglxmxxQueryModel>>.SuccessResult(queryData, totalNumber);
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return ResponseUtil<List<XmglxmxxQueryModel>>.FailResult(null, ex.Message);
            }
        }

        /// <summary>
        /// 新增xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，新增操作结果</param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> PostAsync(RequestPost<XmglxmxxAddModel> requestObject,CurrentUser user)
        {
            var currDb = _db.Instance;
            try
            {
                //如果没有新增数据，返回错误信息
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                var result = false;
                currDb.BeginTran();
                //批量新增的优先级高于单条数据新增，且只会执行一个新增操作
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //查询客户信息
                    var khlist = await currDb.Queryable<XmjckhxxDbModel>().Where(p => p.Deleteflag == 0).ToListAsync();
                    //查询体系信息
                    var txlist = await currDb.Queryable<XmjcgltxDbModel>().Where(p => p.Deleteflag == 0).ToListAsync();
                    foreach(var item in requestObject.PostDataList)
                    {
                        //客户信息是否存在
                        var khmodel = khlist.Where(p => p.Khmc == item.Khmc).FirstOrDefault();
                        if(khmodel != null)
                        {
                            item.Khid = khmodel.ID;
                        }
                        else
                        {
                            var newKh = new XmjckhxxDbModel
                            {
                                ID = 0,
                                Khmc = item.Khmc,
                                Khbm = $"{DateTime.Now:yyMMdd}" + $"{khlist.Count + 1}".PadLeft(4, '0'),
                                Createid = item.Createid,
                                Createname = item.Createname,
                                Createtime = DateTime.Now,
                                Khzt = "Y",
                                Lxdh = item.Lxdh,
                                Lxr = item.Lxr,
                                Lxyx = item.Lxyx,
                                Gsdz = item.Htdz,
                                Ygrs = item.Txrs,
                                Deleteflag = 0
                            };
                            newKh.ID = await currDb.Insertable(newKh).ExecuteReturnIdentityAsync();
                            khlist.Add(newKh);
                            item.Khid = newKh.ID;                            
                        }

                        //体系信息是否存在
                        var txmodel = txlist.Where(p => p.Txmc == item.Txmc && p.Txgg ==  item.Txgg).FirstOrDefault();
                        if(txmodel != null)
                        {
                            item.Txid = txmodel.ID;
                        }
                        else
                        {
                            var newTx = new XmjcgltxDbModel
                            {
                                Txmc = item.Txmc,
                                Txgg = item.Txgg,
                                Txbm = $"{DateTime.Now:yyMMdd}" + $"{txlist.Count + 1}".PadLeft(4, '0'),
                                Createid = item.Createid,
                                Createname = item.Createname,
                                Createtime = DateTime.Now,
                                Rzzq = 3,
                                Rztxzq = 120,
                                Jszq = 1,
                                Jstxzq = 90,
                                Rzbz = item.Rzbz,
                                Lcid = 0//未关联流程模板
                            };
                            newTx.ID = await currDb.Insertable(newTx).ExecuteReturnIdentityAsync();
                            txlist.Add(newTx);
                            item.Txid = newTx.ID;
                        }
                    }

                    var qdlist = await currDb.Queryable<XmjcqdxxDbModel>().Where(p => p.Deleteflag == 0).ToListAsync();
                    //导入主证书信息
                    var mainData = requestObject.PostDataList.Where(p => p.Zslb == "主证书").ToList();
                    foreach (var item in mainData)
                    {
                        var currItem = item;
                        //检索是否有项目信息
                        var flag = await currDb.Queryable<XmglxmxxDbModel>().AnyAsync(p => p.Erpbh == currItem.Erpbh && p.Shlx == p.Shlx);
                        if (flag)
                        {
                            if (currItem.Zsksrq != null && currItem.Zsjsrq != null)
                            {
                                //更新证书信息
                                var khgltx = await currDb.Queryable<XmkhgltxDbModel>()
                                .Where(p => p.Khid == currItem.Khid && p.Txid == currItem.Txid && p.Zslb == currItem.Zslb)
                                .FirstAsync();
                                //var gltx = await currDb.Queryable<XmjcgltxDbModel>().Where(p => p.ID == currItem.Txid).FirstAsync();
                                //var xcshrq = ((DateTime)currItem.Mcshrq).AddYears(gltx.Jszq);
                                //if(currItem.Xctxsj != null)
                                //{
                                //    xcshrq = ((DateTime)currItem.Xctxsj).AddYears(gltx.Jszq);
                                //}
                                if (khgltx == null)
                                {
                                    //不存在该管理体系信息时，新增
                                    var newModel = new XmkhgltxDbModel
                                    {
                                        Createid = user.UserID,
                                        Createname = user.UserName,
                                        Createtime = DateTime.Now,
                                        Deleteflag = 0,
                                        Txid = currItem.Txid,
                                        Khid = currItem.Khid,
                                        Zsrq = (DateTime)currItem.Zsksrq,
                                        Zsjg = "URS",
                                        Zsyxq = (DateTime)currItem.Zsjsrq,
                                        Mcshrq = currItem.Mcshrq,
                                        Xcshrq = currItem.Xctxsj,
                                        Zslb = currItem.Zslb,
                                        Zsh = currItem.Zsh,
                                        Zszt = currItem.Zszt,
                                        Dqshlx = currItem.Shlx
                                    };
                                    await currDb.Insertable(newModel).ExecuteCommandAsync();
                                }
                                else
                                {
                                    if (currItem.Zsjsrq < khgltx.Zsyxq)
                                    {
                                        //旧的证书信息 不处理
                                        continue;
                                    }
                                    //更新
                                    await currDb.Updateable<XmkhgltxDbModel>()
                                        .SetColumns(p => p.Zsrq == (DateTime)currItem.Zsksrq)
                                        .SetColumns(p => p.Zsyxq == (DateTime)currItem.Zsjsrq)
                                        .SetColumns(p => p.Zsjg == "URS")
                                        .SetColumns(p => p.Mcshrq == currItem.Mcshrq)
                                        .SetColumns(p => p.Xcshrq == currItem.Xctxsj)
                                        .SetColumns(p => p.Zszt == currItem.Zszt)
                                        .Where(p => p.ID == khgltx.ID)
                                        .ExecuteCommandAsync();
                                }
                            }
                        }
                        else
                        {
                            if (currItem.Shlx != "监一" && currItem.Shlx != "监二")
                            {
                                currItem.Shxh = 0;
                            }
                            else if (currItem.Shlx == "监一")
                            {
                                currItem.Shxh = 1;
                            }
                            else if (currItem.Shlx == "监二")
                            {
                                currItem.Shxh = 2;
                            }
                            var currQdxx = qdlist.Where(p => p.Qdmc == currItem.Qdmc).FirstOrDefault();
                            if(currQdxx != null)
                            {
                                currItem.Qdid = currQdxx.ID;
                            }
                            var currAddModel = _mapper.Map<XmglxmxxDbModel>(currItem);
                            if(currItem.Shzt == "Y")
                            {
                                currAddModel.Shr = user.UserName;
                                currAddModel.Shsj = DateTime.Now;
                                currAddModel.Pcshr = user.UserName;
                                currAddModel.Pcshsj = DateTime.Now;
                                currAddModel.Pczt = "Y";
                                currAddModel.Pcshzt = "Y";
                                currAddModel.Xmzt = "Y";
                                currAddModel.Xmztqrr = user.UserName;
                                currAddModel.Xmztqrsj = DateTime.Now;
                            }
                            await currDb.Insertable(currAddModel).ExecuteCommandAsync();
                            if (currItem.Zsksrq != null && currItem.Zsjsrq != null)
                            {
                                //更新证书信息
                                var khgltx = await currDb.Queryable<XmkhgltxDbModel>()
                                    .Where(p => p.Khid == currItem.Khid && p.Txid == currItem.Txid && p.Zslb == currItem.Zslb)
                                    .FirstAsync();
                                //var gltx = await currDb.Queryable<XmjcgltxDbModel>().Where(p => p.ID == currItem.Txid).FirstAsync();
                                //var xcshrq = ((DateTime)currItem.Mcshrq).AddYears(gltx.Jszq);
                                //if (currItem.Xctxsj != null)
                                //{
                                //    xcshrq = ((DateTime)currItem.Xctxsj).AddYears(gltx.Jszq);
                                //}
                                if (khgltx == null)
                                {
                                    //不存在该管理体系信息时，新增
                                    var newModel = new XmkhgltxDbModel
                                    {
                                        Createid = user.UserID,
                                        Createname = user.UserName,
                                        Createtime = DateTime.Now,
                                        Deleteflag = 0,
                                        Txid = currItem.Txid,
                                        Khid = currItem.Khid,
                                        Zsrq = (DateTime)currItem.Zsksrq,
                                        Zsjg = "URS",
                                        Zsyxq = (DateTime)currItem.Zsjsrq,
                                        Mcshrq = currItem.Mcshrq,
                                        Xcshrq = currItem.Xctxsj,
                                        Zslb = currItem.Zslb,
                                        Zsh = currItem.Zsh,
                                        Zszt = currItem.Zszt,
                                        Dqshlx = currItem.Shlx
                                    };
                                    await currDb.Insertable(newModel).ExecuteCommandAsync();
                                }
                                else
                                {
                                    if (currItem.Zsjsrq < khgltx.Zsyxq)
                                    {
                                        //旧的证书信息 不处理
                                        continue;
                                    }
                                    //更新
                                    await currDb.Updateable<XmkhgltxDbModel>()
                                        .SetColumns(p => p.Zsrq == (DateTime)currItem.Zsksrq)
                                        .SetColumns(p => p.Zsyxq == (DateTime)currItem.Zsjsrq)
                                        .SetColumns(p => p.Zsjg == "URS")
                                        .SetColumns(p => p.Mcshrq == currItem.Mcshrq)
                                        .SetColumns(p => p.Xcshrq == currItem.Xctxsj)
                                        .SetColumns(p => p.Zszt == currItem.Zszt)
                                        .Where(p => p.ID == khgltx.ID)
                                        .ExecuteCommandAsync();
                                }
                            }
                        }

                    }
                    //导入子证书信息
                    var childData = requestObject.PostDataList.Where(p => p.Zslb == "子证书").ToList();
                    //生成证书信息
                    foreach (var item in childData)
                    {
                        var currItem2 = item;
                        //先插主证书，必然有主记录
                        var mainModel = await currDb.Queryable<XmglxmxxDbModel>()
                            .Where(p => p.Erpbh == currItem2.Erpbh && p.Shlx == currItem2.Shlx &&p.Zslb == "主证书")
                            .FirstAsync();
                        if(mainModel == null)
                        {
                            continue;
                        }
                        //检索是否有项目信息
                        if (currItem2.Shlx != "监一" && currItem2.Shlx != "监二")
                        {
                            currItem2.Shxh = 0;
                        }
                        else if (currItem2.Shlx == "监一")
                        {
                            currItem2.Shxh = 1;
                        }
                        else if (currItem2.Shlx == "监二")
                        {
                            currItem2.Shxh = 2;
                        }
                        if (currItem2.Shzt == "Y")
                        {
                            currItem2.Shr = user.UserName;
                            currItem2.Shsj = DateTime.Now;
                        }
                        var currAddModel = new XmglxmxxzbDbModel()
                        {
                            ID = 0,
                            Bz = currItem2.Bz,
                            Createid = currItem2.Createid,
                            Createname = currItem2.Createname,
                            Createtime = currItem2.Createtime,
                            Csje = currItem2.Csje,
                            Dcslb = currItem2.Dcslb,
                            Deleteflag = currItem2.Deleteflag,
                            Erpbh = currItem2.Erpbh,
                            Shsj = currItem2.Shsj,
                            Sfdcs = currItem2.Sfdcs,
                            Shlx = currItem2.Shlx,
                            Shr = currItem2.Shr,
                            Shxh = currItem2.Shxh,
                            Shzt = currItem2.Shzt,
                            Sxq = currItem2.Sxq,
                            Rzfw = currItem2.Rzfw,
                            Htdz = currItem2.Htdz,
                            Htje = currItem2.Htje,
                            Htlx = currItem2.Htlx,
                            Htqdrq = currItem2.Htqdrq,
                            Jsje = currItem2.Jsje,
                            Khid = currItem2.Khid,
                            Pid = mainModel.ID,
                            Txid = currItem2.Txid,
                            Txrs = currItem2.Txrs,
                            Xmzt = currItem2.Xmzt,
                            Zsh = currItem2.Zsh,
                            Zsjsrq = currItem2.Zsjsrq,
                            Zsksrq = currItem2.Zsksrq,
                            Zslb = currItem2.Zslb,
                            Zydm = currItem2.Zydm,
                            Sf = currItem2.Sf
                        };
                        await currDb.Insertable(currAddModel).ExecuteCommandAsync();
                        if (currItem2.Zsksrq != null && currItem2.Zsjsrq != null)
                        {
                            //更新证书信息
                            var khgltx = await currDb.Queryable<XmkhgltxDbModel>()
                                .Where(p => p.Khid == currItem2.Khid && p.Txid == currItem2.Txid && p.Zslb == currItem2.Zslb)
                                .FirstAsync();
                            //var gltx = await currDb.Queryable<XmjcgltxDbModel>().Where(p => p.ID == currItem.Txid).FirstAsync();
                            //var xcshrq = ((DateTime)currItem.Mcshrq).AddYears(gltx.Jszq);
                            //if (currItem.Xctxsj != null)
                            //{
                            //    xcshrq = ((DateTime)currItem.Xctxsj).AddYears(gltx.Jszq);
                            //}
                            if (khgltx == null)
                            {
                                //不存在该管理体系信息时，新增
                                var newModel = new XmkhgltxDbModel
                                {
                                    Createid = user.UserID,
                                    Createname = user.UserName,
                                    Createtime = DateTime.Now,
                                    Deleteflag = 0,
                                    Txid = currItem2.Txid,
                                    Khid = currItem2.Khid,
                                    Zsrq = (DateTime)currItem2.Zsksrq,
                                    Zsjg = "URS",
                                    Zsyxq = (DateTime)currItem2.Zsjsrq,
                                    Mcshrq = currItem2.Mcshrq,
                                    Xcshrq = currItem2.Xctxsj,
                                    Zslb = currItem2.Zslb,
                                    Zsh = currItem2.Zsh,
                                    Zszt = currItem2.Zszt,
                                    Dqshlx = currItem2.Shlx
                                };
                                await currDb.Insertable(newModel).ExecuteCommandAsync();
                            }
                            else
                            {
                                if (currItem2.Zsjsrq < khgltx.Zsyxq)
                                {
                                    //旧的证书信息 不处理
                                    continue;
                                }
                                //更新
                                await currDb.Updateable<XmkhgltxDbModel>()
                                    .SetColumns(p => p.Zsrq == (DateTime)currItem2.Zsksrq)
                                    .SetColumns(p => p.Zsyxq == (DateTime)currItem2.Zsjsrq)
                                    .SetColumns(p => p.Zsjg == "URS")
                                    .SetColumns(p => p.Mcshrq == currItem2.Mcshrq)
                                    .SetColumns(p => p.Xcshrq == currItem2.Xctxsj)
                                    .SetColumns(p => p.Zszt == currItem2.Zszt)
                                    .Where(p => p.ID == khgltx.ID)
                                    .ExecuteCommandAsync();
                            }
                        }


                    }

                    result = true;
                }
                else
                {
                    var addModel = _mapper.Map<XmglxmxxDbModel>(requestObject.PostData);
                    result = await currDb.Insertable(addModel).ExecuteCommandAsync() > 0;
                }
                currDb.CommitTran();
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "新增数据失败!");
            }
            catch(Exception ex)
            {
                currDb.RollbackTran();
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 新增xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，新增操作结果</param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> CreateAsync(RequestPost<XmglxmxxCreateModel> requestObject, CurrentUser user)
        {
            var currDb = _db.Instance;
            try
            {
                currDb.BeginTran();
                var item = await currDb.Queryable<XmglxmxxDbModel>()
                    .Where(p => p.Khid == requestObject.PostData.Khid && p.Txid == requestObject.PostData.Txid
                    && p.Zsh == requestObject.PostData.Zsh)
                    .FirstAsync();
                if(item == null)
                {
                   return  ResponseUtil<bool>.FailResult(false, "生成项目信息失败，未找到原始项目信息!");
                }
                var item2 = await currDb.Queryable<XmglxmxxDbModel>()
                    .Where(p => p.Khid == requestObject.PostData.Khid && p.Txid == requestObject.PostData.Txid
                    && p.Zsh == requestObject.PostData.Zsh && p.Shxh ==  requestObject.PostData.Shxh)
                    .FirstAsync();
                if (item2 != null)
                {
                    return ResponseUtil<bool>.FailResult(false, "生成项目信息失败，该项目信息已存在!");
                }
                var newModel = new XmglxmxxDbModel
                {
                    ID = 0,
                    Bz = item.Bz,
                    Createid = user.UserID,
                    Createname = user.UserName,
                    Createtime = DateTime.Now,
                    Csje = item.Csje,
                    Dcslb = item.Dcslb,
                    Deleteflag = item.Deleteflag,
                    Erpbh = item.Erpbh,
                    Shsj = null,
                    Sfdcs = item.Sfdcs,
                    Shlx = requestObject.PostData.Shxh == 1 ? "监一" : "监二",
                    Shr = null,
                    Shxh = requestObject.PostData.Shxh,
                    Shzt = "N",
                    Sxq = item.Sxq,
                    Rzfw = item.Rzfw,
                    Htdz = item.Htdz,
                    Htje = item.Htje,
                    Htlx = item.Htlx,
                    Htqdrq = item.Htqdrq,
                    Jsje = item.Jsje,
                    Khid = item.Khid,
                    Txid = item.Txid,
                    Txrs = item.Txrs,
                    Xmzt = "N",
                    Zsh = item.Zsh,
                    Zsjsrq = item.Zsjsrq,
                    Zsksrq = item.Zsksrq,
                    Zslb =item.Zslb,
                    Zydm = item.Zydm,
                    Sf = item.Sf,
                    Pczt = "N",
                    Skzt = "N",
                    Kpzt = "N",
                    Pcshzt = "N",
                    Lcmb = item.Lcmb,
                    Qdid = item.Qdid,
                    Txids = item.Txids
                };
                await currDb.Insertable(newModel).ExecuteCommandAsync();
                
                currDb.CommitTran();
                //返回执行结果
                return ResponseUtil<bool>.SuccessResult(true);
            }
            catch (Exception ex)
            {
                currDb.RollbackTran();
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> PutAsync(RequestPut<XmglxmxxEditModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量更新
                    var editList = _mapper.Map<List<XmglxmxxDbModel>>(requestObject.PostDataList);
                    result = await _db.Instance.Updateable(editList)
                        .IgnoreColumns(p => new {
                            p.Createid,
                            p.Createtime,
                            p.Createname,
                            p.Shr,
                            p.Shzt,
                            p.Shsj,
                            p.Pcshr,
                            p.Pcshsj,
                            p.Pcshzt,
                            p.Pczt,
                            p.Skqrr,
                            p.Skqrsj,
                            p.Skzt,
                            p.Kpqrr,
                            p.Kpqrsj,
                            p.Kpzt,
                            p.Xmzt,
                            p.Xmztqrr,
                            p.Xmztqrsj
                        })
                        .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录更新
                    var editModel = _mapper.Map<XmglxmxxDbModel>(requestObject.PostData);
                    result = await _db.Instance.Updateable(editModel)
                        .IgnoreColumns(p => new {
                            p.Createid,
                            p.Createtime,
                            p.Createname,
                            p.Shr,
                            p.Shzt,
                            p.Shsj,
                            p.Pcshr,
                            p.Pcshsj,
                            p.Pcshzt,
                            p.Pczt,
                            p.Skqrr,
                            p.Skqrsj,
                            p.Skzt,
                            p.Kpqrr,
                            p.Kpqrsj,
                            p.Kpzt,
                            p.Xmzt,
                            p.Xmztqrr,
                            p.Xmztqrsj
                        })
                        .ExecuteCommandAsync() > 0;
                }
                
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "修改数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> UpdateCertificateAsync(RequestPut<XmglxmxxDoneModel> requestObject, CurrentUser user)
        {
            var currDb = _db.Instance;
            try
            {
                var xmxx = await currDb.Queryable<XmglxmxxDbModel>()
                    .Where(p => p.ID == requestObject.PostDataList[0].ID)
                    .FirstAsync();

                foreach(var item in requestObject.PostDataList)
                {
                    await currDb.Deleteable<XmkhgltxDbModel>()
                        .Where(p => p.Khid == xmxx.Khid && p.Txid == item.Txid)
                        .ExecuteCommandAsync();

                    var mcshrq = await currDb.Queryable<XmglxmxxlcDbModel>()
                        .Where(p => p.Xmid == xmxx.ID && p.Sfxcsh == "Y")
                        .MaxAsync(p => p.Jsrq);
                    var xcshrq = ((DateTime)mcshrq).AddMonths(9);
                    //不存在该管理体系信息时，新增
                    var zsList = new List<string>();
                    if (item.Zsh.IndexOf(',') > -1)
                    {
                        zsList = item.Zsh.Split(",").ToList();
                    }
                    else
                    {
                        zsList.Add(item.Zsh);
                    }
                    var newModelList = new List<XmkhgltxDbModel>();
                    for (var i = 0; i < zsList.Count; i++)
                    {
                        if (string.IsNullOrEmpty(zsList[i]))
                            continue;
                        var newModel = new XmkhgltxDbModel
                        {
                            Createid = user.UserID,
                            Createname = user.UserName,
                            Createtime = DateTime.Now,
                            Deleteflag = 0,
                            Txid = item.Txid,
                            Khid = xmxx.Khid,
                            Zsrq = (DateTime)item.Zsrq,
                            Zsjg =  item.Zsjg,
                            Zsyxq = (DateTime)item.Zsyxq,
                            Mcshrq = mcshrq,
                            Xcshrq = xcshrq,
                            Zsh = zsList[i],
                            Zslb = "子证书",
                            Zszt = "有效",
                            Dqshlx = xmxx.Shlx,
                            Qrzt = "Y",
                            Fhxzmh = item.Fhxzmh
                        };
                        if (i == 0)
                        {
                            newModel.Zslb = "主证书";
                        }
                        newModelList.Add(newModel);
                    }
                    await currDb.Insertable(newModelList).ExecuteCommandAsync();
                }

                //返回执行结果
                return ResponseUtil<bool>.SuccessResult(true);
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> AuditAsync(RequestPut<XmglxmxxAuditModel> requestObject, CurrentUser user)
        {
            var currDb = _db.Instance;
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                currDb.BeginTran();
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量更新
                    var editList = _mapper.Map<List<XmglxmxxDbModel>>(requestObject.PostDataList);

                    foreach(var item in requestObject.PostDataList)
                    {
                        //生成流程明细数据
                        var xmxx = await currDb.Queryable<XmglxmxxDbModel>().Where(p => p.ID == item.ID).FirstAsync();
                        var lcxx = new List<XmjclcxxfbDbModel>();
                        if (xmxx.Lcmb != null)
                        {
                            lcxx = await currDb.Queryable<XmjclcxxfbDbModel>()
                               .Where(p => p.Lczid == xmxx.Lcmb && p.Deleteflag == 0)
                               .OrderBy(p => p.Lcxh)
                               .ToListAsync();
                        }
                        else
                        {
                            lcxx = await currDb.Queryable<XmjclcxxfbDbModel>()
                            .Where(p => p.Lczid == SqlFunc.Subqueryable<XmjcgltxDbModel>().Where(p1 => p1.ID == xmxx.Txid)
                                                    .Select(p1 => (int)p1.Lcid) &&
                            p.Deleteflag == 0)
                            .OrderBy(p => p.Lcxh)
                            .ToListAsync();
                        }
                        if(lcxx == null || lcxx.Count == 0)
                        {
                            return ResponseUtil<bool>.FailResult(false, "管理体系未关联执行流程模板，审核失败");
                        }
                        //删除原流程信息
                        await currDb.Deleteable<XmglxmxxlcDbModel>().Where(p => p.Xmid == item.ID).ExecuteCommandAsync();
                        foreach (var item2 in lcxx)
                        {
                            var xmxxlcModel = new XmglxmxxlcDbModel
                            {
                                ID = 0,
                                Xmid = item.ID,
                                Createid = user.UserID,
                                Createname = user.UserName,
                                Createtime = DateTime.Now,
                                Deleteflag = 0,
                                Lcmc = item2.Lcmc,
                                Lcxh = item2.Lcxh,
                                Sfxcsh = item2.Sfxcsh,
                                Xxtxlx = item2.Lcjdid
                            };
                            await currDb.Insertable(xmxxlcModel).ExecuteCommandAsync();
                        }
                    }

                    result = await currDb.Updateable(editList)
                        .UpdateColumns(p => new { p.Shr, p.Shzt, p.Shsj })
                        .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录更新
                    var editModel = _mapper.Map<XmglxmxxDbModel>(requestObject.PostData);
                    var xmxx = await currDb.Queryable<XmglxmxxDbModel>().Where(p => p.ID == requestObject.PostData.ID).FirstAsync();
                    //生成流程明细数据                    
                    //var xmTxid = await currDb.Queryable<XmglxmxxDbModel>().Where(p => p.ID == requestObject.PostData.ID).Select(p => p.Txid).FirstAsync();
                    if(requestObject.PostData.Shzt == "Y")
                    {
                        //生成流程明细信息
                        var lcxx = new List<XmjclcxxfbDbModel>();
                        if (xmxx.Lcmb != null)
                        {
                            lcxx = await currDb.Queryable<XmjclcxxfbDbModel>()
                               .Where(p => p.Lczid == xmxx.Lcmb && p.Deleteflag == 0)
                               .OrderBy(p => p.Lcxh)
                               .ToListAsync();
                        }
                        else
                        {
                            lcxx = await currDb.Queryable<XmjclcxxfbDbModel>()
                            .Where(p => p.Lczid == SqlFunc.Subqueryable<XmjcgltxDbModel>().Where(p1 => p1.ID == xmxx.Txid)
                                                    .Select(p1 => (int)p1.Lcid) &&
                            p.Deleteflag == 0)
                            .OrderBy(p => p.Lcxh)
                            .ToListAsync();
                        }
                        await currDb.Deleteable<XmglxmxxlcDbModel>().Where(p => p.Xmid == requestObject.PostData.ID).ExecuteCommandAsync();
                        foreach (var item in lcxx)
                        {
                            var xmxxlcModel = new XmglxmxxlcDbModel
                            {
                                ID = 0,
                                Xmid = editModel.ID,
                                Createid = user.UserID,
                                Createname = user.UserName,
                                Createtime = DateTime.Now,
                                Deleteflag = 0,
                                Lcmc = item.Lcmc,
                                Lcxh = item.Lcxh,
                                Sfxcsh = item.Sfxcsh
                            };
                            await currDb.Insertable(xmxxlcModel).ExecuteCommandAsync();
                        }
                        result = await currDb.Updateable(editModel)
                            .UpdateColumns(p => new { p.Shr, p.Shzt, p.Shsj })
                            .ExecuteCommandAsync() > 0;
                    }
                    else
                    {
                        //反审核删除流程信息
                        await currDb.Deleteable<XmglxmxxlcDbModel>()
                            .Where(p => p.Xmid == requestObject.PostData.ID)
                            .ExecuteCommandAsync();
                        editModel.Shr = "";
                        editModel.Shsj = null;
                        result = await currDb.Updateable(editModel)
                            .UpdateColumns(p => new { p.Shr, p.Shzt, p.Shsj })
                            .ExecuteCommandAsync() > 0;
                    }

                                        
                }
                currDb.CommitTran();
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "修改数据失败!");
            }
            catch (Exception ex)
            {
                currDb.RollbackTran();
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> SchedulingAuditAsync(RequestPut<XmglxmxxAuditModel> requestObject)
        {
            var currDb = _db.Instance;
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                currDb.BeginTran();

                var lcList = await currDb.Queryable<XmglxmxxlcDbModel>()
                    .Where(p => p.Xmid == requestObject.PostData.ID)
                    .ToListAsync();

                if (lcList.Any(p => p.Sfxcsh == "Y" && (p.Ksrq == null || p.Jsrq == null || string.IsNullOrEmpty(p.Shyid))))
                {
                    return ResponseUtil<bool>.FailResult(false, "审核失败，排程信息不完整");
                }
                //排程人员信息检查互斥性
                //获取当前项目已排程人员信息
                var currProList = await currDb.Queryable<XmglxmxxpcDbModel, XmglxmxxlcDbModel>(
                    (t, t1) => new object[] { JoinType.Left, t.Xmid == t1.Xmid && t.Xmlcid == t1.ID })
                    .Where((t,t1) => t.Xmid == requestObject.PostData.ID)
                    .Select((t, t1) => new
                    {
                        t.ID,t.Kssj,t.Jssj,t.Shyid,t1.Lcxh,t.Shy
                    })
                    .ToListAsync();

                //本次行程互斥检查
                //每个阶段内比较
                //阶段与阶段比较
                foreach (var item in currProList)
                {
                    //获取本次行程中，相同流程阶段相同人员的排程信息
                    var currUserProList = currProList
                        .Where(p => p.ID != item.ID && p.Shyid == item.Shyid)
                        .ToList();
                    //和其他行程比较
                    foreach (var item2 in currUserProList)
                    {
                        if (item.Jssj >= item2.Kssj && item.Lcxh <= item2.Lcxh)
                        {
                            return ResponseUtil<bool>.FailResult(false, "审核失败，当前项目内行程有冲突");
                        }
                    }

                }
                var today = Convert.ToDateTime($"{DateTime.Now:yyyy-MM-dd}");
                //其他项目行程互斥检查
                foreach (var item in currProList)
                {
                    var currItem = item;
                    //查询其他项目，行程结束日期大于等于今天的数据，其他的认为行程已结束
                    var otherProList = await currDb.Queryable<XmglxmxxpcDbModel,XmglxmxxDbModel,XmjckhxxDbModel,XmjcgltxDbModel>(
                        (t,t1,t2,t3) => new object[] {
                            JoinType.Left , t.Xmid == t1.ID,
                            JoinType.Left , t1.Khid == t2.ID,
                            JoinType.Left , t1.Txid == t3.ID
                        })
                        .Where((t,t1,t2,t3) => t.Xmid != requestObject.PostData.ID && t.Shyid == currItem.Shyid && t1.Pcshzt == "Y")
                        .Select((t,t1,t2,t3) => new {t.Kssj,t.Jssj,t2.Khmc,t3.Txmc,t1.Shlx,t.Shy})
                        .ToListAsync();
                    foreach (var item2 in otherProList)
                    {
                        //本次行程的开始时间小于其他行程的结束时间
                        if ((currItem.Kssj >= item2.Kssj && currItem.Kssj <= item2.Jssj) || (currItem.Jssj >= item2.Kssj && currItem.Jssj <= item2.Jssj))
                        {
                            return ResponseUtil<bool>.FailResult(false, $"审核失败，{item2.Shy}与[{item2.Khmc}][{item2.Txmc}][{item2.Shlx}]行程有冲突");
                        }
                    }
                }

                //更新排程状态信息
                await currDb.Updateable<XmglxmxxDbModel>()
                .SetColumns(p => p.Pcshr == requestObject.PostData.Shr)
                .SetColumns(p => p.Pcshzt == requestObject.PostData.Shzt)
                .SetColumns(p => p.Pcshsj == requestObject.PostData.Shsj)
                .SetColumns(p => p.Pczt == "Y")
                .Where(p => p.ID == requestObject.PostData.ID)
                .ExecuteCommandAsync();


                currDb.CommitTran();
                //返回执行结果
                return ResponseUtil<bool>.SuccessResult(true);
            }
            catch (Exception ex)
            {
                currDb.RollbackTran();
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> SchedulingAuditCancelAsync(RequestPut<XmglxmxxAuditModel> requestObject)
        {
            var currDb = _db.Instance;
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                currDb.BeginTran();

                result = await currDb.Updateable<XmglxmxxDbModel>()
                    .SetColumns(p => p.Pcshr == null)
                    .SetColumns(p => p.Pcshzt == "N")
                    .SetColumns(p => p.Pcshsj == null)
                    .SetColumns(p => p.Pczt == "N")
                    .Where(p => p.ID == requestObject.PostData.ID)
                    .ExecuteCommandAsync() > 0;


                currDb.CommitTran();
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "修改数据失败!");
            }
            catch (Exception ex)
            {
                currDb.RollbackTran();
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> ReceiveConfirmAsync(RequestPut<XmglxmxxAuditModel> requestObject)
        {
            var currDb = _db.Instance;
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                currDb.BeginTran();
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    foreach(var item in requestObject.PostDataList)
                    {
                        await currDb.Updateable<XmglxmxxDbModel>()
                        .SetColumns(p => p.Skzt == item.Shzt)
                        .SetColumns(p => p.Skqrr == item.Shr)
                        .SetColumns(p => p.Skqrsj == item.Shsj)
                        .Where(p => p.ID == item.ID)
                        .ExecuteCommandAsync();
                    }
                    result = true;
                }
                else
                {
                    result = await currDb.Updateable<XmglxmxxDbModel>()
                        .SetColumns(p => p.Skzt == requestObject.PostData.Shzt)
                        .SetColumns(p => p.Skqrr == requestObject.PostData.Shr)
                        .SetColumns(p => p.Skqrsj == requestObject.PostData.Shsj)
                        .Where(p => p.ID == requestObject.PostData.ID)
                        .ExecuteCommandAsync() > 0;
                }
                currDb.CommitTran();
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "确认数据失败!");
            }
            catch (Exception ex)
            {
                currDb.RollbackTran();
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> DoneConfirmAsync(RequestPut<XmglxmxxDoneModel> requestObject,CurrentUser user)
        {
            var currDb = _db.Instance;
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                currDb.BeginTran();

                var xmxx = await currDb.Queryable<XmglxmxxDbModel>()
                    .Where(p => p.ID == requestObject.PostData.ID)
                    .FirstAsync();

                //更新项目状态
                await currDb.Updateable<XmglxmxxDbModel>()
                    .SetColumns(p => p.Xmzt == requestObject.PostData.Xmzt)
                    .SetColumns(p => p.Xmztqrr == requestObject.PostData.Xmztqrr)
                    .SetColumns(p => p.Xmztqrsj == requestObject.PostData.Xmztqrsj)
                    .Where(p => p.ID == requestObject.PostData.ID)
                    .ExecuteCommandAsync();
                //判断证书是否更新

                if (xmxx.Shlx == "监一" || xmxx.Shlx == "监二")
                {
                    if (string.IsNullOrEmpty(xmxx.Txids))
                    {
                        var khgltx = await currDb.Queryable<XmkhgltxDbModel>()
                            .Where(p => p.Khid == xmxx.Khid && p.Txid == xmxx.Txid)
                            .ToListAsync();
                        if (khgltx.Count == 0)
                        {
                            //缺少证书信息，提示先维护
                            currDb.RollbackTran();
                            return ResponseUtil<bool>.FailResult(false, "项目完结确认失败，请先维护该客户当前体系的证书信息,包括子证书信息!");
                        }
                        var xcshrq = ((DateTime)khgltx[0].Mcshrq).AddMonths(21);
                        //更新
                        await currDb.Updateable<XmkhgltxDbModel>()
                            .SetColumns(p => p.Dqshlx == xmxx.Shlx)
                            .SetColumns(p => p.Xcshrq == xcshrq)
                            .SetColumns(p => p.Zszt == "有效")
                            .SetColumns(p => p.Qrzt == "Y")
                            .Where(p => p.ID == khgltx[0].ID)
                            .ExecuteCommandAsync();
                    }
                    else
                    {
                        var txids = Array.ConvertAll(xmxx.Txids.Split(','), s => int.TryParse(s, out int i) ? i : 0);
                        foreach (var txid in txids)
                        {
                            var khgltx = await currDb.Queryable<XmkhgltxDbModel>()
                                .Where(p => p.Khid == xmxx.Khid && p.Txid == txid)
                                .ToListAsync();
                            if (khgltx.Count == 0)
                            {
                                //缺少证书信息，提示先维护
                                currDb.RollbackTran();
                                return ResponseUtil<bool>.FailResult(false, "项目完结确认失败，请先维护该客户当前体系的证书信息,包括子证书信息!");
                            }
                            var xcshrq = ((DateTime)khgltx[0].Mcshrq).AddMonths(21);
                            //更新
                            await currDb.Updateable<XmkhgltxDbModel>()
                                .SetColumns(p => p.Dqshlx == xmxx.Shlx)
                                .SetColumns(p => p.Xcshrq == xcshrq)
                                .SetColumns(p => p.Zszt == "有效")
                                .SetColumns(p => p.Qrzt == "Y")
                                .Where(p => p.ID == khgltx[0].ID)
                                .ExecuteCommandAsync();
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(xmxx.Txids))
                    {
                        var khgltx = await currDb.Queryable<XmkhgltxDbModel>()
                            .Where(p => p.Khid == xmxx.Khid && p.Txid == xmxx.Txid)
                            .ToListAsync();
                        var bcshsj = await currDb.Queryable<XmglxmxxlcDbModel>()
                            .Where(p => p.Xmid == xmxx.ID && p.Sfxcsh == "Y")
                            .MaxAsync(p => p.Jsrq);
                        if (bcshsj >= khgltx[0].Zsrq)
                        {
                            //未更新证书信息
                            currDb.RollbackTran();
                            return ResponseUtil<bool>.FailResult(false, "项目完结确认失败，本次审核体系存在未更新的证书信息!");
                        }
                    }
                    else
                    {
                        var txids = Array.ConvertAll(xmxx.Txids.Split(','), s => int.TryParse(s, out int i) ? i : 0);
                        foreach (var txid in txids)
                        {
                            var khgltx = await currDb.Queryable<XmkhgltxDbModel>()
                                .Where(p => p.Khid == xmxx.Khid && p.Txid == txid)
                                .ToListAsync();

                            var bcshsj = await currDb.Queryable<XmglxmxxlcDbModel>()
                            .Where(p => p.Xmid == xmxx.ID && p.Sfxcsh == "Y")
                            .MaxAsync(p => p.Jsrq);
                            if (bcshsj >= khgltx[0].Zsrq)
                            {
                                //未更新证书信息
                                currDb.RollbackTran();
                                return ResponseUtil<bool>.FailResult(false, "项目完结确认失败，本次审核体系存在未更新的证书信息!");
                            }
                        }

                    }
                }

                result = true;
                currDb.CommitTran();
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "确认数据失败!");
            }
            catch (Exception ex)
            {
                currDb.RollbackTran();
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 修改xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象，包括响应代码，修改操作结果</param>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> InvoiceConfirmAsync(RequestPut<XmglxmxxAuditModel> requestObject)
        {
            var currDb = _db.Instance;
            try
            {
                //执行结果
                var result = false;
                //没有修改信息，返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData,PostDataList不能都为null");
                currDb.BeginTran();
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    foreach (var item in requestObject.PostDataList)
                    {
                        await currDb.Updateable<XmglxmxxDbModel>()
                        .SetColumns(p => p.Kpzt == item.Shzt)
                        .SetColumns(p => p.Kpqrr == item.Shr)
                        .SetColumns(p => p.Kpqrsj == item.Shsj)
                        .Where(p => p.ID == item.ID)
                        .ExecuteCommandAsync();
                    }
                    result = true;
                }
                else
                {
                    result = await currDb.Updateable<XmglxmxxDbModel>()
                        .SetColumns(p => p.Kpzt == requestObject.PostData.Shzt)
                        .SetColumns(p => p.Kpqrr == requestObject.PostData.Shr)
                        .SetColumns(p => p.Kpqrsj == requestObject.PostData.Shsj)
                        .Where(p => p.ID == requestObject.PostData.ID)
                        .ExecuteCommandAsync() > 0;
                }
                currDb.CommitTran();
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "确认数据失败!");
            }
            catch (Exception ex)
            {
                currDb.RollbackTran();
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }

        /// <summary>
        /// 删除xm_gl_xmxx数据
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        public async Task<ResponseObject<bool>> DeleteAsync(RequestDelete<DeleteModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有删除数据，返回错误信息
                if (requestObject.PostData == null && requestObject.PostDataList == null)
                    return ResponseUtil<bool>.FailResult(false, "PostData、PostDataList不能都为null");
                //批量删除的优先级高于单记录删除
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量删除
                    var ids = requestObject.PostDataList.Select(p => p.ID);
                    result = await _db.Instance.Updateable<XmglxmxxDbModel>()
                            .SetColumns(p => p.Deleteflag == 1)
                            .Where(p => ids.Contains(p.ID))
                            .ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录删除
                    result = await _db.Instance.Updateable<XmglxmxxDbModel>()
                        .SetColumns(p => p.Deleteflag == 1)
                        .Where(p => p.ID == requestObject.PostData.ID)
                        .ExecuteCommandAsync() > 0;
                }
                //返回执行结果
                return result ? ResponseUtil<bool>.SuccessResult(true) : ResponseUtil<bool>.FailResult(false, "删除数据失败!");
            }
            catch (Exception ex)
            {
                //返回异常结果
                return ResponseUtil<bool>.FailResult(false, ex.Message);
            }
        }
        
    }
}
